# h1=. views.py

# p=. *Quiz View Definitions* 
# _jrlf 2013-02-08_

# h2. Front Matter

# h3. Imports

import datetime

from utilities import herf

from django.utils import simplejson
from django.db.models import Q
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.template import RequestContext
from django.core.exceptions import ObjectDoesNotExist

import models

# h2. Views

# h3. Quiz Overview

def index(request):
    "( request -- response) Render overview page."

    return HttpResponse("Top level for Quiz.")


def entree(texts, parent=None, data=None):
    if not data: data = [None,]
    
    items = sorted([x for x in texts if x.parent == parent], 
                   key=lambda o: o.order)
    if not len(items): return parent # Leaf node.

    for i in items:
        data.append(entree(texts, i, [i,]))
    return data


# h3. envelop()

# Build HTML from tree. Override options display with @listing@ parm.

def envelop(tree, heading=1, listing=None):
    html = []
    
    section = tree[0]
    if section: html.append(["h%d" % heading, section.text])
    
    ul = []
    for branch in tree[1:]:
        if type(branch) in (type(()), type([])):
            html.extend(envelop(branch, heading+1, listing))
        else: ul.append(branch)

    if ul:
        if listing: html.append(listing(ul))
        else: html.append(["ul",] + [["li", o.text] for o in ul])

    return html
        

def ballot(request, id):
    "( request id -- response) Display ballot."

    quiz = get_object_or_404(models.Quiz, id=int(id))

    def options(ul):
        html = ["div",]
        for i in ul:
            html.extend([
                    ["input", {"name": "%s" % i.parent.id, "type": "radio", "id": "%s" % i.id}],
                    ["label", {"for": "%s" % i.id}, i.text]
                ])
        return html

    body = ["div",
            ["div", quiz.about],
            ["form", {"method": "post", "action": "/quiz/%d/answering/" % quiz.id},] +
            envelop(entree(quiz.questions.all()), listing=options),
            ]
    if quiz.open(): body[-1].append(
        ["button", {"class": "btn", "type": "submit"}, "answer"])

    parms = dict(title = quiz.title,
                 body  = herf.herf(body),
                 css   = "",
                 script = "")
    return render_to_response(
        "quiz_base.html", parms,
        context_instance=RequestContext(request))


def answering(request, id):
    "( request id -- response) Submit ballot answers."

    quiz = get_object_or_404(models.Quiz, id=int(id))

    for key in request.POST.keys():
        print "%s -> %s" % (key, request.POST[key])
    
    return redirect(ballot, id=quiz.id, context_instance=RequestContext(request))
    
